package cn.itcast.dlq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 死信队列消费者
 *
 * @author lee.siu.wah
 * @version 1.0
 * <p>File Created at 2020-11-24<p>
 */
@Component
public class DeadLetterConsumer {

    /**
     * 消息监听方法
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dlx-queue"), // 队列
            key = "#", // 路由键
            exchange = @Exchange(name="dlx.exchange",
                    type = ExchangeTypes.TOPIC)))
    public void handlerMessage(String msg, Channel channel, Message message){
        try {
            System.out.println("===============");
            System.out.println("死信队列--->接受到的消息是：" + msg);
//            int i = 10 /0;
//            // 手动确认
//            /**
//             * long deliveryTag 消息唯一标识
//             * boolean multiple 单条或批量
//             */
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception ex){
            try {
                // 把死信队列中的消息写入数据库表。

                /**
                 * 拒绝确认
                 * long deliveryTag: 消息唯一id
                 * boolean requeue: 是否重投
                 */
                //channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }catch (Exception e){

            }
        }
    }
}